<template>
  <div :id="containerId" style="position: relative">
    <!-- <input
      v-if="!changeDisabled"
      type="file"
      :multiple="multiple"
      class="select-file-input"
      :accept="accept"
      οnclick="f.outerHTML=f.outerHTML"
      @change="handleFileChange"
    /> -->
    <a-upload
      :file-list="fileList"
      :remove="handleRemove"
      :before-upload="beforeUpload"
      accept=".mp4"
      :disabled="fileList.length > 0 && uploading"
    >
      <a-button> <a-icon type="upload" /> 选择大文件（不超过2G） </a-button>
    </a-upload>
    <a-button
      type="primary"
      :disabled="fileList.length === 0 || uploaded"
      :loading="uploading"
      style="margin-top: 16px"
      @click="handleUpload"
    >
      {{ uploading ? `上传中:${process}%` : uploaded ? '转码中...' : '开始上传' }}
    </a-button>
    <a-button
      type="primary"
      :disabled="fileList.length === 0 || !uploaded"
      style="margin-top: 16px;margin-left: 20px"
      @click="resetUpload"
    >
      重新上传
    </a-button>
  </div>
</template>

<script>
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { getFileAccessHttpUrl, httpAction } from '@/api/manage'
import axios from 'axios'
import { v4 as uuidv4 } from 'uuid'

var chunkSize = 2 * 1024 * 1024 // 切片大小
var instance = axios.create({})
var uploadUrl = process.env.VUE_APP_UPLOAD_SERVER

export default {
  name: 'VideoUpload',
  data() {
    return {
      fileList: [],
      uploading: false,
      maxSize: 1024 * 1024 * 1024 * 10,
      process: '0',
      uploaded: false,
      uuid: ''
    }
  },
  props: {},

  computed: {},
  created() {
    console.log(process.env)
    const token = Vue.ls.get(ACCESS_TOKEN)
    this.headers = { 'X-Access-Token': token }
    this.containerId = 'container-ty-' + new Date().getTime()
  },
  methods: {
    handleRemove(file) {
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
    },
    beforeUpload(file) {
      this.fileList = [...this.fileList, file]
      console.log(this.fileList)
      return false
    },
    handleUpload() {
      const { fileList } = this
      const that = this
      this.uploading = true
      const fileChunkList = this.createFileChunk(fileList[0], chunkSize)
      const uuid = uuidv4()
      var successNum = 0
      var totalChunk = fileChunkList.length
      fileChunkList.forEach((chunk, index) => {
        const formData = new FormData()
        formData.append('guid', uuid)
        formData.append('chunk', index)
        formData.append('file', chunk.file)
        formData.append('type', fileList[0].type)
        instance.post(uploadUrl + '/upload', formData).then(res => {
          console.log('handler -> res', res)
          setTimeout(() => {
            successNum++
            if (successNum == totalChunk) {
              that.process = '100'
              that.mergeChunk(uuid, fileList[0].name, totalChunk)
            } else {
              that.process = parseFloat((successNum / totalChunk) * 100).toFixed(2)
            }
          }, 1000)
        })
      })
    },
    // 创建文件切片
    createFileChunk(file, size) {
      const fileChunkList = []
      var count = 0
      while (count < file.size) {
        fileChunkList.push({
          file: file.slice(count, count + size)
        })
        count += size
      }
      return fileChunkList
    },
    mergeChunk(uuid, name, totalChunk) {
      const that = this
      const formData = new FormData()
      formData.append('guid', uuid)
      formData.append('fileName', name)
      formData.append('total', totalChunk)
      httpAction(uploadUrl + '/merge', formData, 'post').then(res => {
        console.log('handler -> res', res)
        that.uuid = uuid
        that.uploading = false
        that.uploaded = true
        that.uploadSuccess(uuid, name)
      })
    },
    resetUpload() {
      this.fileList = []
      this.uploaded = false
      this.uuid = ''
    },
    uploadSuccess(uuid, filename) {
      this.$emit('uploaded', { uuid: uuid, filename: filename })
    }
  },
  mounted() {},
  model: {
    prop: 'value',
    event: 'change'
  }
}
</script>

<style lang="less"></style>
